import $ from 'jquery'
import _common from '../commonJs/wptx_common'
import _validate from '../commonJs/wptx_validate'
/** *************************************/
/*          全局的变量 START            */
/** *************************************/
const logLv = _common.log_lv

export default {
    debug: debug, // log  debug
    info: info, // log  info
    warn: warn, // log  warn
    error: error, // log  error
    reset: reset, // 清空检索条件
    saveSessionStorage: saveSessionStorage, // 判断页面跳转传递过来时候，传递的参数是否为空 （初始化时候使用）
    getSessionStorage: getSessionStorage, // 判断页面跳转传递过来时候，传递的参数是否为空 （页面调用时候使用）
    cloneObj: cloneObj, // 深度拷贝对象
    openTip: openTip, // 页面头部弹出的提示
    addActive: addActive, // 设置导航选中项
    uuid: uuid, // 生成uuid的随机数
    ntime: ntime, // 获取当前时间
    dtime: dtime, // 时间戳转成时间格式
    PrefixInteger: PrefixInteger, // 个位数补0方法 （num, length） num传入的值 length数值的位数  例： （1，2）返回 01 （1，3）返回 001
    matchingString: matchingString, // 字符串匹配之前的所有
    pickDataList: pickDataList, // 转成 pickData 格式
    pickDataLists: pickDataLists, // 转成 pickData 格式(单个数据用)
    Retain: Retain,
    getUrlParamValue: getUrlParamValue, // 从URL中根据参数名称获取参数值
    enter: enter, // 回车转换为半角逗号
    commaTo:commaTo, // 逗号转回车
    commaTofeng:commaTofeng, // ;转回车
    blankSpace:blankSpace, // 是否是空格
    getTime: getTime,
    deepCompare: deepCompare, //判断两个对象是否相等
    getFileExtName: getFileExtName,
    getErrMsg: getErrMsg,
    enterJoin: enterJoin,

}
/** 解析返回值的ErrMsg */
function getErrMsg(resultData) {
    if (_validate.checkEmpty(resultData)) {
        return "";
    }
    let errMsg = "";
    if (!_validate.checkEmpty(resultData.msg)) {
        errMsg += resultData.msg;
    }
    if (!_validate.checkEmpty(resultData.message)) {
        if (_validate.checkEmpty(errMsg)) {
            errMsg += resultData.message;
        } else {
            errMsg += "," + resultData.message;
        }
    }
    return errMsg;
}
/** 获取文件扩展名 */
function getFileExtName(fileName) {
    if (_validate.checkEmpty(fileName)) {
        return "";
    }
    let pos = fileName.lastIndexOf(".");
    if (pos < 0) {
        return "";
    }
    return fileName.substring(pos).toLowerCase();
}
/** 判断两个对象是否相等 */
function deepCompare(x, y) {
    let i, l, leftChain, rightChain;

    function compare2Objects(x, y) {
        let p;

        // remember that NaN === NaN returns false
        // and isNaN(undefined) returns true
        if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
            return true;
        }

        // Compare primitives and functions.
        // Check if both arguments link to the same object.
        // Especially useful on the step where we compare prototypes
        if (x === y) {
            return true;
        }

        // Works in case when functions are created in constructor.
        // Comparing dates is a common scenario. Another built-ins?
        // We can even handle functions passed across iframes
        if ((typeof x === 'function' && typeof y === 'function') ||
            (x instanceof Date && y instanceof Date) ||
            (x instanceof RegExp && y instanceof RegExp) ||
            (x instanceof String && y instanceof String) ||
            (x instanceof Number && y instanceof Number)) {
            return x.toString() === y.toString();
        }

        // At last checking prototypes as good as we can
        if (!(x instanceof Object && y instanceof Object)) {
            return false;
        }

        if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
            return false;
        }

        if (x.constructor !== y.constructor) {
            return false;
        }

        if (x.prototype !== y.prototype) {
            return false;
        }

        // Check for infinitive linking loops
        if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
            return false;
        }

        // Quick checking of one object being a subset of another.
        // todo: cache the structure of arguments[0] for performance
        for (p in y) {
            if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                return false;
            } else if (typeof y[p] !== typeof x[p]) {
                return false;
            }
        }

        for (p in x) {
            if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                return false;
            } else if (typeof y[p] !== typeof x[p]) {
                return false;
            }

            switch (typeof(x[p])) {
                case 'object':
                case 'function':

                    leftChain.push(x);
                    rightChain.push(y);

                    if (!compare2Objects(x[p], y[p])) {
                        return false;
                    }

                    leftChain.pop();
                    rightChain.pop();
                    break;

                default:
                    if (x[p] !== y[p]) {
                        return false;
                    }
                    break;
            }
        }

        return true;
    }

    if (arguments.length < 1) {
        return true; //Die silently? Don't know how to handle such case, please help...
        // throw "Need two or more arguments to compare";
    }

    for (i = 1, l = arguments.length; i < l; i++) {

        leftChain = []; //Todo: this can be cached
        rightChain = [];

        if (!compare2Objects(arguments[0], arguments[i])) {
            return false;
        }
    }

    return true;
}
//  回车转换为半角逗号
function enter(value, num) {
    if (value == undefined || value == null || value === '') {
        return ""
    }
    let no = ''
    if(_validate.checkEmpty(num)){
        no = ','
    }else{
        no = num
    }
    if(no == ';'){
        value = value.replace(/\n/g, no);
    }else{
        value = value.replace(/\n/g, no);
        value = value.replace(/\r/g, no);
    }
    return value
}
// 逗号转回车
function commaTo(value){
    let str = value
    if (value == undefined || value == null || value === '') {
        return ""
    }
    let reg = /[,，]/g;
    str = str.replace(reg,"\r\n");
    return str
}
// ;转回车
function commaTofeng(value){
    let str = value
    if (value == undefined || value == null || value === '') {
        return ""
    }
    let reg = /[;；]/g;
    str = str.replace(reg,"\r\n");
    return str
}
// 是否是空格
function blankSpace(value){
    let str = value
    let regu = "^[ ]+$";
    if (str == undefined || str == null || str === '') {
        return true
    }
    let re = new RegExp(regu);
    return re.test(str)
}
// 保留两位小数
function Retain(data) {
    if (data == undefined || data == null || data == '') {
        data = 0
    } else {
        data = (data / 100).toFixed(2)
    }
    return data
}
/* 转成 pickData 格式*/
function pickDataList(data) {
    let dataList = []
    data.map(item => {
        if (item != null && item != undefined && item != '') {
            const pickDataObject = {}
            pickDataObject.text = item
            pickDataObject.value = item
            dataList.push(pickDataObject)
        } else {
            dataList = []
        }
    })
    const obj = {}
    obj.text = '请选择'
    obj.value = -1
    dataList.unshift(obj)
    return dataList
}
/* 转成 pickData 格式*/
function pickDataLists(data) {
    const dataList = []

    if (data != null && data != undefined && data != '') {
        const pickDataObject = {}
        pickDataObject.text = data
        pickDataObject.value = data
        dataList.push(pickDataObject)
    }

    return dataList
}
/* 获取匹配字符串之前的 */
function matchingString(dataString) {
    var index = dataString.lastIndexOf('\ ')
    var obj = dataString.substring(0, index + 1)
    return obj
}

/* 深度拷贝对象 */
function cloneObj(obj) {
    var str;
    var newobj = obj.constructor === Array ? [] : {}
    if (typeof obj !== 'object') {
        return
    } else if (window.JSON) {
        str = JSON.stringify(obj), // 序列化对象
            newobj = JSON.parse(str) // 还原
    } else {
        for (var i in obj) {
            newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i]
        }
    }
    return newobj
}

/** *************************************/
/*          通用方法 START              */
/** *************************************/
function debug(...vars) {
    const len = vars.length
    if (logLv > 3) {
        for (let i = 0; i < len; i++) {
        }
    }
}

function info(...vars) {
    const len = vars.length
    if (logLv > 2) {
        for (let i = 0; i < len; i++) {
        }
    }
}

function warn(...vars) {
    const len = vars.length
    if (logLv > 1) {
        for (let i = 0; i < len; i++) {
        }
    }
}

function error(...vars) {
    const len = vars.length
    if (logLv > 0) {
        for (let i = 0; i < len; i++) {
        }
    }
}

/*  清空检索  */
function reset(currObj, initObj) {
    $.each(currObj, function(name, val) {
        if (val != undefined && val != null && $.trim(val) != '') {
            currObj[name] = ''
        }
    })
}

/* 判断页面跳转传递过来时候，传递的参数是否为空 （初始化时候使用）*/
function saveSessionStorage(paramName, paramValue) {
    if (typeof(paramValue) === 'boolean') {
        sessionStorage.setItem(paramName, paramValue)
    }

    if (_validate.checkEmptyTrim(paramName)) {
        return
    }
    if (_validate.checkEmptyTrim(paramValue)) {
        return
    }
    paramValue = _validate.getValue(paramValue)
    sessionStorage.setItem(paramName, paramValue)
}

/* 判断页面跳转传递过来时候，传递的参数是否为空（页面调用时候使用） */
function getSessionStorage(paramName, paramValue) {
    if (_validate.checkEmptyTrim(paramName)) {
        return null
    }
    if (_validate.checkEmptyTrim(paramValue)) {
        paramValue = sessionStorage.getItem(paramName)
        if (_validate.checkEmptyTrim(paramValue)) {
            return null
        } else {
            return paramValue
        }
    } else {
        return paramValue
    }
}

/** 提示信息
 * @param vm
 * @param message { String } -必选 提示内容
 * @param type { String } -可选 提示信息的类型 失败：error 警告：warning 成功：success 默认为消息
 */
function openTip(vm, msg, type) {
    vm.$message({
        message: msg,
        showClose: true, // { Boolean  } -可选 提示信息是否可手动关闭
        type: type
    })
}
/** 设置导航选中项
 * @param obj */
function addActive(opt) {
    const obj = $('#' + opt)
    if (obj) {
        obj.addClass('is-active')
    }
}
/** uuid 的随机数
 * @param len 长度
 * @param radix 基数
 */
function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    var uuid = []
    var i
    radix = radix || chars.length
    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
    } else {
        var r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
            }
        }
    }
    return uuid.join('')
}
/** 获取当前时间
 * @param fmt {boolean} ture(yyyy - MM - dd) ; false(yyyy - MM - dd hh: mm)
 **/
function ntime(fmt = true) {
    const myDate = new Date()
    let newtime = ''
    if (fmt) {
        newtime = myDate.getFullYear() + '-' + (myDate.getMonth() + 1 < 10 ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1) + '-' + '-' + (myDate.getDate() < 10 ? '0' + (myDate.getDate()) : myDate.getDate())
    } else {
        newtime = myDate.getFullYear() + '-' + (myDate.getMonth() + 1 < 10 ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1) + '-' + '-' + (myDate.getDate() < 10 ? '0' + (myDate.getDate()) : myDate.getDate()) + ' ' + myDate.getHours() + ':' + myDate.getMinutes() + ':' + myDate.getSeconds()
    }
    return newtime
}
/** 时间戳转换成时间
 * @param fmt {boolean} -ture(yyyy - MM - dd) ; false(yyyy - MM - dd hh: mm)
 * @param inputTime { Number } -必选 需要转换的时间戳
 **/
function dtime(inputTime, fmt = true) {
    var datetime = new Date(inputTime)
    const Ytime = datetime.getFullYear() + '-'
    const Mtime = (datetime.getMonth() + 1 < 10 ? '0' + (datetime.getMonth() + 1) : datetime.getMonth() + 1) + '-'
    const Dtime = (datetime.getDate() < 10 ? '0' + (datetime.getDate()) : datetime.getDate())
    const htime = (datetime.getHours() < 10 ? '0' + (datetime.getHours()) : datetime.getHours()) + ':'
    const mtime = (datetime.getMinutes() < 10 ? '0' + (datetime.getMinutes()) : datetime.getMinutes()) + ':'
    const stime = (datetime.getSeconds() < 10 ? '0' + (datetime.getSeconds()) : datetime.getSeconds())
    let newtime = ''
    if (fmt) {
        newtime = newtime + Ytime + Mtime + Dtime
    } else {
        newtime = newtime + Ytime + Mtime + Dtime + ' ' + htime + mtime + stime
    }
    return newtime
}
/** 提示信息
 * @param num 传入的值
 * @param length 所需的位数
 */
function PrefixInteger(num, length) {
    return (Array(length).join('0') + num).slice(-length)
}

function getUrlParamValue(url, paramName) {
    if (url.indexOf("?") < 1) {
        return null;
    }
    let paramStr = url.substr(url.indexOf("?") + 1);
    let paramList = paramStr.split("&");
    if (_validate.checkListEmpty(paramList)) {
        return null;
    }
    let currParamStr = "";
    let currParamList = null;
    let currKey = "";
    let currValue = "";
    for (let cnt = 0; cnt < paramList.length; cnt++) {
        currParamStr = paramList[cnt];
        if (_validate.checkEmptyTrim(currParamStr)) {
            continue;
        }
        if (currParamStr.indexOf("=") < 1) {
            continue;
        }
        currParamList = currParamStr.split("=");
        if (_validate.checkListEmpty(currParamStr)) {
            continue;
        }
        if (currParamList.length != 2) {
            continue;
        }
        currKey = currParamList[0];
        currValue = currParamList[1];
        if (currKey == paramName) {
            return currValue;
        }
    }
    return null;

}
//  20191022151547576  这样格式的时间
function getTime() {
    let myDate = new Date();
    let value = myDate.getFullYear() + "" + (myDate.getMonth() + 1) + "" + myDate.getDate() + "" + myDate.getHours() + "" + myDate.getMinutes() + "" + myDate.getSeconds() + "" + myDate.getMilliseconds()
    return value
}

/**
 * 回车转换字符串
 */
function enterJoin(value) {
    if (value === "" || value === null || value === undefined) {
      return ""
    } else {
      let temp = $.trim(value).split(/[\n+,，]/g);
      for (var i = 0; i < temp.length; i++) {
        if (temp[i] == "") {
          temp.splice(i, 1);
          i--;
        } else {
          temp[i] = temp[i].replace(/[\s+]/g, "");
        }
      }
      return temp.join(',');
    }
  }
